package com.huaxonline.boot.web.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 带启动日志的跨域自动配置类
 */
@Configuration
@EnableConfigurationProperties(CorsProperties.class)
@ConditionalOnProperty(name = "huaxonline.cors.enabled", havingValue = "true")
public class CorsAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(CorsAutoConfiguration.class);
    private final CorsProperties corsProperties;

    // 构造函数注入配置属性
    public CorsAutoConfiguration(CorsProperties corsProperties) {
        this.corsProperties = corsProperties;
    }

    /**
     * 注册跨域过滤器，带启动日志
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        // 打印生效日志
        log.debug("====== 跨域配置已生效 ======");
        log.debug("允许的源: {}", corsProperties.getAllowedOrigins());
        log.debug("允许的方法: {}", corsProperties.getAllowedMethods());
        log.debug("允许的请求头: {}", corsProperties.getAllowedHeaders());
        log.debug("是否允许凭据: {}", corsProperties.isAllowCredentials());
        log.debug("预检缓存时间: {}秒", corsProperties.getMaxAge());
        log.debug("适用路径: {}", corsProperties.getPathPatterns());
        log.debug("==========================");

        // 创建跨域配置
        CorsConfiguration config = new CorsConfiguration();
        corsProperties.getAllowedOrigins().forEach(config::addAllowedOrigin);
        corsProperties.getAllowedMethods().forEach(config::addAllowedMethod);
        corsProperties.getAllowedHeaders().forEach(config::addAllowedHeader);
        config.setAllowCredentials(corsProperties.isAllowCredentials());
        config.setMaxAge(corsProperties.getMaxAge());

        // 配置路径映射
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(corsProperties.getPathPatterns(), config);

        // 注册过滤器并设置最高优先级
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

}
